package com.shengzai.rdd

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext, util}

object Demo23Acc{
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local[4]")
    conf.setAppName("join")
    val sc = new SparkContext(conf)

    val stuRDD: RDD[String] = sc.textFile("data/students.txt")

    /**
     * 累加器:累加器可以在转换算子中计算，这样可以避免多个action算子，增加job，性能高
     */

    val acc: util.LongAccumulator = sc.longAccumulator
    val mapRDD: RDD[Int] = stuRDD.map(
      line => {
        val split: Array[String] = line.split(",")
        acc.add(1)
        split(2).toInt
      }
    )
    val avgAge: Double = mapRDD.sum() / acc.value

    println(avgAge)

  }
}
